package servlet;

import dao.MessageDao;
import entity.Message;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 新增留言
 */
@WebServlet("/AddMessageServlet")
public class AddMessageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取请求参数
        req.setCharacterEncoding("utf-8");
        String userId = req.getParameter("userId");
        String msgContent = req.getParameter("msgContent");

        //2. 向数据库中留言表插入数据
        JSONObject resData = new JSONObject();
        resData.put("code", 200);
        //创建时间：
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //创建留言实例对象
        Message message = new Message(null, Integer.parseInt(userId), msgContent, sdf.format(new Date()));
        MessageDao messageDao = new MessageDao();
        try {
            boolean b = messageDao.addMessage(message);
            resData.put("data", b);
        } catch (SQLException e) {
            e.printStackTrace();
            resData.put("data", false);
        }
        //3.响应数据给前端调用者：
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println(resData);
        writer.flush();
        writer.close();

    }
}
